package com.buba.springcloud.controller;

import com.buba.springcloud.pojo.CommonResult;
import com.buba.springcloud.pojo.Document;
import com.buba.springcloud.service.IDocumentService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
public class DocumentController {

    public static final Logger logger = LoggerFactory.getLogger(DocumentController.class);

    //注入服务发现的注解
    @Autowired
    private DiscoveryClient discoveryClient;

//    @Autowired
//    private DocumentMapper documentMapper;

    @Autowired
    private IDocumentService documentService;


    @Value("${server.port}")
    private String serverPort;

//    pdf分片加载
    @CrossOrigin(methods = RequestMethod.GET)
    @GetMapping("/loadPdf/{pdfName}")
    public void loadPdf(@PathVariable("pdfName") String pdfName, HttpServletResponse response, HttpServletRequest request) throws FileNotFoundException, UnsupportedEncodingException {
        // 获取当前系统的默认字符编码并打印
//        String charset = System.getProperty("file.encoding");
//        System.out.println("当前系统默认编码: " + charset);

        documentService.loadPDFByPage(pdfName, response, request);
//        为了解决中文乱码问题
//        documentService.loadPDFByPage(URLDecoder.decode(pdfName,"utf-8"), response, request);
    }

    @CrossOrigin(methods = RequestMethod.POST)
//    @CrossOrigin(value = {"http://localhost:8080","http://localhost:8081","http://127.0.0.1:8081","http://honglitech.cn","http://honglitech.cn:8081","http://honglitech.cn:8080"})
//    @CrossOrigin(origins = "*",maxAge = 3600)
    @PostMapping("/document/upload")
//    @RequiresPermissions("adImage:update")
//    @ControllerEndpoint(operation = "上传图片", exceptionMessage = "上传图片失败")
    public CommonResult upload(@RequestParam("file") MultipartFile mf){
        //临时设定一个user
        Integer userId = 1;
//        public CommonResult upload(@RequestPart("file") MultipartFile mf){
        String uploadUrl = documentService.upload(mf, userId);
        if(null != uploadUrl){
            return new CommonResult(200,"查询成功",uploadUrl);
        }else{
            return new CommonResult(444,"上传失败",null);
        }
    }

    @RequestMapping(value = "document/consul")
    public String DocumentConsul() {
        return "SpringCloud with consul:" + serverPort + "\t" + UUID.randomUUID().toString();
    }

//    @CrossOrigin(methods = RequestMethod.GET)
//    @GetMapping("/document/getTest/{id}")
//    public CommonResult queryById(@PathVariable("id") Long id){
////        SuppliesAround suppliesAround = materialMapper.selectById(id);
//        log.info("***************成功触发到ducument的getOne*********"+id);
//        if(id!=null){
//            return new CommonResult(200,"查询成功",id);
//        }else{
//            return new CommonResult(444,"查询失败",null);
//        }
//    }

    @CrossOrigin(methods = RequestMethod.GET)
    @GetMapping("/document/getList/{userId}")
    public CommonResult getList(@PathVariable("userId") Integer userId){
//        System.out.println("进入获取文档列表接口，表示有人访问testweb项目指定页面链接，一次有两");
        List<Document> list = documentService.selectList(userId);
//        log.info("***************查询成功*********"+list);
        if(list!=null){
            return new CommonResult(200,"查询成功",list);
        }else{
            return new CommonResult(444,"查询失败",null);
        }
    }

    /**
     * 查询product_id回给前端
     */
    @CrossOrigin(methods = RequestMethod.GET)
    @GetMapping("/document/detailByName/{name}")
    public CommonResult detailByName(@PathVariable("name") String name) throws UnsupportedEncodingException {
        Document aDocDetail = documentService.detailByName(URLDecoder.decode(name,"utf-8"));
        return new CommonResult(200,"查询成功",aDocDetail);
    }

    /**
     * 下载文件
     *
     *            文件唯一识别码(经URLEncoder编码)
     * @param res
     */
    @RequestMapping(value = "/showpdf", method = RequestMethod.GET)
    public void showpdf(HttpServletRequest req, HttpServletResponse res) {
        try {
            this.download(req, res);
        } catch (Exception e) {
//             e.printStackTrace();
            logger.error("错误信息:{}", e.getMessage(), e);
        }
    }
    /**
     * 下载文件
     */
    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 从文件存储服务器下载文件到本地
        File file = new File("D:/test.pdf");
        BufferedInputStream bis = null;
        OutputStream os = null;
        BufferedOutputStream bos = null;
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            bis = new BufferedInputStream(is);
            os = response.getOutputStream();
            bos = new BufferedOutputStream(os);
            // 下载的字节范围
            int startByte, endByte, totalByte;
            if (request != null && request.getHeader("range") != null) {
                // 起始字节大小
                String[] range = request.getHeader("range").replaceAll("[^0-9\\-]", "").split("-");
                // 文件总大小
                totalByte = is.available();
                // 下载起始位置
                startByte = Integer.parseInt(range[0]);
                // 下载结束位置
                if (range.length > 1) {
                    endByte = Integer.parseInt(range[1]);
                } else {
                    endByte = totalByte - 1;
                }


                // 返回http状态
                response.setStatus(206);
            } else {
                // 正常下载
                // 文件总大小
                totalByte = is.available();

                // 下载起始位置
                startByte = 0;
                // 下载结束位置
                endByte = totalByte - 1;
                // 返回http状态
                response.setHeader("Accept-Ranges", "bytes");
                response.setStatus(206);
            }
            // 需要下载字节数
            int length = endByte - startByte;
            // 响应头
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + totalByte);
            response.setContentType("application/octet-stream");//Content-Type: application/octet-stream
            response.setContentLength(length);
            // 响应内容
            bis.skip(startByte);
            int len = 0;
            byte[] buff = new byte[1024 * 64];
            while ((len = bis.read(buff, 0, buff.length)) != -1) {
                if (length <= len) {
                    bos.write(buff, 0, length);
                    break;
                } else {
                    length -= len;
                    bos.write(buff, 0, len);
                }
            }
        } catch (IOException e) {
            System.out.println("下载中断!");
            logger.error("错误信息:{}", e.getMessage(), e);
        } finally {
            bos.close();
            os.close();
            bis.close();
            is.close();
        }
    }

/*
    @CrossOrigin(methods = RequestMethod.POST)
    @PostMapping("/feedback/save")
    public CommonResult saveMaterialApplication(@RequestBody(required=false) Feedback feedback){
        log.info("***************开始保存*********");

        int result = this.feedbackMapper.insert(feedback);
        log.info("***************保存申请成功*********"+result);
        if(result!=0){
            return new CommonResult(200,"保存成功",feedback);
        }else{
            return new CommonResult(444,"保存失败",null);
        }
    }

    //获取服务信息
    @GetMapping("/feedback/discovery")
    public  Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String s : services){
            log.info("********注册到eureka中的服务中有:"+services);
        }
        List <ServiceInstance> instances = discoveryClient.getInstances("epidemic-material");
        for (ServiceInstance s: instances) {
            log.info("当前服务的实例有"+s.getServiceId()+"\t"+s.getHost()+"\t"+s.getPort()+"\t"+s.getUri());
        }
        return this.discoveryClient;
    }
 */

}
